package com.mall.order.services;

import com.alibaba.fastjson.JSON;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.HashMap;

@Component
public class RocketProvider {

    DefaultMQProducer defaultMQProducer;

    @PostConstruct
    public void init(){
        defaultMQProducer = new DefaultMQProducer("producer_group");

        defaultMQProducer.setNamesrvAddr("localhost:9876");

        try {
            defaultMQProducer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

        System.out.println("消息生产者初始化成功！！");
    }

    public boolean handleProvider(String orderId) {

        System.out.println("provider orderId:"+orderId);

        HashMap<String, Object> map = new HashMap<>();
        map.put("order",orderId);

        String jsonStr = JSON.toJSONString(map);

        Message message = new Message("order", jsonStr.getBytes(Charset.forName("utf-8")));


        // 这个地方可以去设置消息的延迟级别
        // delayTimeLevel 18个延迟级别，不可更改
        // 1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
        message.setDelayTimeLevel(14);
        try {
            SendResult sendResult = defaultMQProducer.send(message);

            if (SendStatus.SEND_OK .equals(sendResult.getSendStatus())) {
                return Boolean.TRUE;
            }
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return true;
    }
}
